{% load static %} {% load custom_filters %}
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>配置数据源 - {{ datasource.name }} - 数据源管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" />
    <style>
      .sidebar {
        height: 100vh;
        background-color: #343a40;
        color: white;
        padding-top: 20px;
      }
      .sidebar .nav-link {
        color: #adb5bd;
        border-radius: 0;
      }
      .sidebar .nav-link.active {
        background-color: #0d6efd;
        color: white;
      }
      .content {
        padding: 20px;
      }
      .form-group {
        margin-bottom: 1.5rem;
      }
      .card-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid rgba(0, 0, 0, 0.125);
      }
      .table-selection {
        max-height: 400px;
        overflow-y: auto;
        border: 1px solid #e9ecef;
        border-radius: 0.25rem;
        padding: 1rem;
      }
      .table-item {
        margin-bottom: 1rem;
        border: 1px solid #dee2e6;
        border-radius: 0.25rem;
        overflow: hidden;
      }
      .table-header {
        background-color: #f8f9fa;
        padding: 0.75rem 1rem;
        border-bottom: 1px solid #dee2e6;
      }
      .table-fields {
        padding: 0.75rem 1rem;
      }
      .field-item {
        margin-left: 1.5rem;
      }
      .badge {
        font-size: 0.75rem;
        margin-left: 0.5rem;
      }
      .field-type {
        color: #334155;
        background-color: #f1f5f9;
        padding: 0.15rem 0.35rem;
        border-radius: 0.2rem;
        margin-left: 0.5rem;
        font-weight: 500;
      }
      .field-description {
        color: #475569;
        margin-left: 0.5rem;
        font-style: normal;
        opacity: 0.9;
      }
      .nullable-badge {
        background-color: #f0fdf4;
        color: #166534;
        border: 1px solid #dcfce7;
        font-size: 0.7rem;
      }
      .not-nullable-badge {
        background-color: #fff1f2;
        color: #b91c1c;
        border: 1px solid #ffccd5;
        font-size: 0.7rem;
      }

      /* 表格整体样式 */
      .centered-table {
        margin: 0 auto; /* 表格居中显示在页面中 */
        border-collapse: collapse; /* 合并边框 */
      }

      /* 表头和内容单元格居中 */
      .centered-table th,
      .centered-table td {
        text-align: center; /* 文本水平居中 */
        vertical-align: middle; /* 文本垂直居中） */
        padding: 10px; /* 单元格内边距 */
        border: 1px solid #ddd; /* 边框样式 */
      }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    {{ datasource.id|json_script:"datasourceId" }} {{ saved_config|json_script:"savedConfig" }}
    <div class="container-fluid">
      <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-2 d-none d-md-block sidebar">
          <div class="text-center mb-4">
            <h3>数据管理</h3>
          </div>
          <ul class="nav flex-column">
            <li class="nav-item">
              <a class="nav-link" href="{% url 'datasource_list' %}">
                <i class="bi bi-database me-2"></i>
                数据源管理
              </a>
            </li>
            <!-- <li class="nav-item">
              <a class="nav-link" href="{% url 'agent_management' %}">
                <i class="bi bi-robot me-2"></i>
                智能体管理
              </a>
            </li> -->
            <li class="nav-item">
              <a class="nav-link" href="{% url 'operation_log' %}">
                <i class="bi bi-clock-history me-2"></i>
                操作日志
              </a>
            </li>
          </ul>
        </div>

        <!-- 主内容区 -->
        <main class="col-md-10 ms-sm-auto px-md-4 content">
          <!-- 顶部导航 -->
          <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
            <div class="container-fluid">
              <a href="{% url 'datasource_list' %}" class="btn btn-outline-secondary me-2">
                <i class="bi bi-arrow-left me-1"></i>
                返回列表
              </a>
              <h4 class="mb-0">配置数据源: {{ datasource.name }}</h4>
              <div class="d-flex ms-auto gap-2">
                <a href="{% url 'datasource_edit' datasource.id %}" class="btn btn-outline-secondary">
                  <i class="bi bi-pencil me-1"></i>
                  编辑基本信息
                </a>
                <button class="btn btn-outline-secondary">
                  <i class="bi bi-person me-1"></i>
                  登录
                </button>
              </div>
            </div>
          </nav>

          <!-- 配置卡片 -->
          <div class="card mb-4">
            <div class="card-header">
              <ul class="nav nav-tabs card-header-tabs">
                <li class="nav-item">
                  <a class="nav-link active" id="data-exposure-tab" data-bs-toggle="tab" href="#data-exposure">数据配置</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="sql-config-tab" data-bs-toggle="tab" href="#sql-config">SQL配置</a>
                </li>
              </ul>
            </div>
            <div class="card-body">
              <div class="tab-content">
                <div class="tab-pane fade show active" id="data-exposure">
                  <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="mb-0">表和字段选择</h5>
                    <span class="text-muted">数据库: {{ datasource.engine }} - {{ datasource.database }}</span>
                  </div>
                  <form method="post">
                    {% csrf_token %}

                    <!-- 连接状态 -->
                    {% if datasource.connection_status %}
                    <div class="alert alert-info d-flex align-items-center mb-4">
                      <i class="bi bi-info-circle me-2">已成功连接到数据库，共发现 {{ datasource.table_count }} 个表。请选择需要同步的数据表及字段。</i>
                    </div>
                    {% else %}
                    <div class="alert alert-danger d-flex align-items-center mb-4">
                      <i class="bi bi-exclamation-circle me-2">未连接到数据库，请先配置数据源连接信息。</i>
                    </div>
                    {% endif %}

                    <!-- 表选择区域 -->
                    <div class="table-selection" id="tableSelectionSection">
                      <!-- 表和字段将通过JavaScript动态生成 -->
                      <div class="text-center text-muted py-5" id="loadingIndicator">
                        <div class="spinner-border text-primary mb-2" role="status"></div>
                        <div>加载表和字段信息中...</div>
                      </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="d-flex justify-content-end gap-2 mt-4">
                      <button type="button" class="btn btn-outline-secondary" id="selectAllBtn">全选</button>
                      <button type="button" class="btn btn-outline-secondary" id="deselectAllBtn">取消全选</button>
                      <button type="button" class="btn btn-primary" id="saveToDbBtn">保存配置</button>
                      <button type="button" class="btn btn-success" id="saveConfigBtn">
                        <i class="bi bi-download me-1"></i>
                        导出配置到JSON
                      </button>
                    </div>
                  </form>
                </div>
                <div class="tab-pane fade" id="sql-config">
                  <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="mb-0">SQL配置管理</h5>
                    <button type="button" class="btn btn-primary" id="addSqlConfigBtn">
                      <i class="bi bi-plus me-1"></i>
                      添加SQL配置
                    </button>
                  </div>

                  <!-- SQL配置列表 -->
                  <div class="table-responsive mb-4" id="sqlConfigList">
                    <table class="table table-striped table-hover centered-table">
                      <thead>
                        <tr>
                          <th>名称</th>
                          <th>描述</th>
                          <th>创建时间</th>
                          <th>操作</th>
                        </tr>
                      </thead>
                      <tbody id="sqlConfigTableBody">
                        <!-- SQL配置列表将通过JavaScript动态生成 -->
                        <tr>
                          <td colspan="4" class="text-center text-muted">加载SQL配置中...</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>

    <!-- SQL配置模态框 -->
    <div class="modal fade" id="sqlConfigModal" tabindex="-1" aria-labelledby="sqlConfigModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="sqlConfigModalLabel">添加SQL配置</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form id="sqlConfigForm">
              <input type="hidden" id="sqlConfigId" value="" />
              <div class="mb-3">
                <label for="sqlConfigName" class="form-label">名称</label>
                <input type="text" class="form-control" id="sqlConfigName" required />
              </div>
              <div class="mb-3">
                <label for="sqlConfigDescription" class="form-label">描述</label>
                <textarea class="form-control" id="sqlConfigDescription" rows="3"></textarea>
              </div>
              <div class="mb-3">
                <label for="sqlConfigType" class="form-label">配置类型</label>
                <select class="form-select" id="sqlConfigType" required>
                  <option value="custom">自定义SQL</option>
                  <option value="table_fields">表字段选择</option>
                </select>
              </div>

              <!-- 自定义SQL配置区域 -->
              <div id="customSqlSection" class="mb-3">
                <label for="sqlConfigSql" class="form-label">SQL语句</label>
                <textarea class="form-control" id="sqlConfigSql" rows="5" required></textarea>
              </div>
              <div id="customSqlParamsSection" class="mb-3">
                <label for="sqlConfigParams" class="form-label">SQL参数(用;分隔)</label>
                <textarea class="form-control" id="sqlConfigParams" rows="1"></textarea>
              </div>

              <!-- 表字段选择配置区域 -->
              <div id="tableFieldsSection" class="mb-3 d-none">
                <div class="mb-3">
                  <div id="joinTablesContainer">
                    <div class="join-table-item mb-3">
                      <label class="form-label">主表</label>
                      <select class="form-select main-table-select"></select>
                    </div>
                  </div>
                  <button type="button" class="btn btn-sm btn-outline-secondary mb-3" id="addJoinTableBtn">+ 添加关联表</button>
                  <div id="joinConditionsContainer"></div>
                </div>
                <div class="mb-3">
                  <label class="form-label">选择字段</label>
                  <div id="sqlConfigFields" class="table-selection"></div>
                </div>
                <div class="mb-3">
                  <label for="sqlConfigWhereField" class="form-label">WHERE条件字段 (可多选，按住Ctrl键选择)</label>
                  <select class="form-select" id="sqlConfigWhereField" multiple size="4"></select>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" id="saveSqlConfigBtn">保存</button>
          </div>
        </div>
      </div>
    </div>

    <!-- SQL配置查看模态框 -->
    <div class="modal fade" id="sqlConfigViewModal" tabindex="-1" aria-labelledby="sqlConfigViewModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="sqlConfigViewModalLabel">查看SQL配置</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <dl class="row">
              <dt class="col-sm-3">名称</dt>
              <dd class="col-sm-9" id="viewSqlConfigName"></dd>

              <dt class="col-sm-3">描述</dt>
              <dd class="col-sm-9" id="viewSqlConfigDescription"></dd>

              <dt class="col-sm-3">SQL语句</dt>
              <dd class="col-sm-9">
                <pre><code id="viewSqlConfigSql"></code></pre>
              </dd>

              <dt class="col-sm-3">SQL参数</dt>
              <dd class="col-sm-9" id="viewSqlConfigParams"></dd>
            </dl>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
          </div>
        </div>
      </div>
    </div>

    <script>
      $(document).ready(function () {
        // 获取数据源ID和已保存的配置
        const datasourceId = JSON.parse(document.getElementById('datasourceId').textContent)
        let savedConfig = JSON.parse(document.getElementById('savedConfig').textContent)
        let fieldsContainerState
        console.log(savedConfig)

        // 初始化SQL配置列表
        loadSqlConfigs()

        // SQL配置标签页显示事件
        $('#sql-config-tab').on('click', function () {
          // 延迟加载，确保标签页已显示
          setTimeout(function () {
            // 总是加载表列表，无论当前配置类型是什么
            loadTablesForSqlConfig()
          }, 100)
        })

        // 当SQL配置模态框显示时，加载表列表
        $('#sqlConfigModal').on('shown.bs.modal', function () {
          loadTablesForSqlConfig()
        })

        // 配置类型切换事件
        $('#sqlConfigType').change(function () {
          const configType = $(this).val()
          if (configType === 'custom') {
            $('#customSqlSection').removeClass('d-none')
            $('#customSqlParamsSection').removeClass('d-none')
            $('#tableFieldsSection').addClass('d-none')
          } else {
            $('#customSqlSection').addClass('d-none')
            $('#customSqlParamsSection').addClass('d-none')
            $('#tableFieldsSection').removeClass('d-none')
          }
        })

        // 添加关联表按钮事件
        $('#addJoinTableBtn').click(function () {
          const joinIndex = $('.join-table-item').length
          const newJoinTableItem = $(`
            <div class="join-table-item mb-3">
              <label class="form-label">关联表 ${joinIndex}</label>
              <select class="form-select join-table-select" data-join-index="${joinIndex - 1}"></select>
            </div>
          `)
          $('#joinTablesContainer').append(newJoinTableItem)

          // 加载表列表
          let parsedConfig
          if (typeof savedConfig === 'string') {
            try {
              parsedConfig = JSON.parse(savedConfig)
            } catch (e) {
              parsedConfig = savedConfig
            }
          } else {
            parsedConfig = savedConfig
          }
          const tables = parsedConfig.tables || []
          const selectedTables = tables.map((table) => table.table) || []

          const joinTableSelect = newJoinTableItem.find('.join-table-select')
          joinTableSelect.append('<option value="">请选择关联表</option>')
          if (selectedTables.length > 0) {
            selectedTables.forEach((table) => {
              joinTableSelect.append(`<option value="${table}">${table}</option>`)
            })
          }

          // 绑定change事件
          joinTableSelect.on('change', function () {
            const tableName = $(this).val()
            const joinIndex = $(this).data('join-index')
            if (tableName) {
              loadFieldsForSqlConfig(tableName, 'join', joinIndex)
            }
          })

          // 添加关联条件
          const joinConditionItem = $(`
            <div class="join-condition-item mb-3 p-3 border rounded" id="joinCondition_${joinIndex - 1}">
              <h6>关联条件 ${joinIndex}</h6>
              <div class="row">
                <div class="col-md-5">
                  <label class="form-label">主表字段</label>
                  <select class="form-select main-table-field-select"></select>
                </div>
                <div class="col-md-2 d-flex align-items-center justify-content-center">
                  <span class="text-center">=</span>
                </div>
                <div class="col-md-5">
                  <label class="form-label">关联表字段</label>
                  <select class="form-select join-table-field-select"></select>
                </div>
              </div>
              <button type="button" class="btn btn-sm btn-danger mt-2 remove-join-condition" data-join-index="${joinIndex - 1}">移除</button>
            </div>
          `)
          $('#joinConditionsContainer').append(joinConditionItem)

          // 绑定移除按钮事件
          joinConditionItem.find('.remove-join-condition').on('click', function () {
            const joinIndex = $(this).data('join-index')
            $(`#joinCondition_${joinIndex}`).remove()
            $(`.join-table-item:eq(${joinIndex + 1})`).remove()

            // 更新后续项的索引
            $(`.join-table-select`).each(function (index) {
              if (index > 0) {
                $(this).data('join-index', index - 1)
              }
            })
            $(`.join-condition-item`).each(function (index) {
              $(this).attr('id', `joinCondition_${index}`)
              $(this).find('.remove-join-condition').data('join-index', index)
              $(this)
                .find('h6')
                .text(`关联条件 ${index + 1}`)
            })
          })

          // 加载主表字段到关联条件
          const mainTableName = $('.main-table-select').val()
          if (mainTableName) {
            let parsedConfig
            if (typeof savedConfig === 'string') {
              try {
                parsedConfig = JSON.parse(savedConfig)
              } catch (e) {
                parsedConfig = savedConfig
              }
            } else {
              parsedConfig = savedConfig
            }
            const tables = parsedConfig.tables || []
            const tableConfig = tables.find((t) => t.table === mainTableName)
            const selectedFields = tableConfig
              ? tableConfig.fields.map((field) => {
                  return field.includes('.') ? field.split('.')[1] : field
                })
              : []

            const mainTableFieldSelect = joinConditionItem.find('.main-table-field-select')
            mainTableFieldSelect.empty()
            if (selectedFields.length > 0) {
              selectedFields.forEach((field) => {
                mainTableFieldSelect.append(`<option value="${field}">${field}</option>`)
              })
            }
          }
        })

        // 初始化添加关联表按钮事件监听
        $(document).on('click', '#addJoinTableBtn', function () {
          // 事件处理已在上面定义
        })

        // 初始化移除关联条件按钮事件监听
        $(document).on('click', '.remove-join-condition', function () {
          // 事件处理已在上面定义
        })

        // 添加SQL配置按钮点击事件
        $('#addSqlConfigBtn').click(function () {
          clearSqlConfigForm()
          $('#sqlConfigModalLabel').text('添加SQL配置')
          $('#sqlConfigModal').modal('show')
        })

        // 清空SQL配置表单
        function clearSqlConfigForm() {
          $('#sqlConfigId').val('')
          $('#sqlConfigName').val('')
          $('#sqlConfigDescription').val('')
          $('#sqlConfigSql').val('')
          $('#sqlConfigParams').val('')
          $('#sqlConfigType').val('custom')

          // 显示自定义SQL区域，隐藏表字段选择区域
          $('#customSqlSection').removeClass('d-none')
          $('#customSqlParamsSection').removeClass('d-none')
          $('#tableFieldsSection').addClass('d-none')

          // 清空表字段选择相关控件
          $('.main-table-select').val('')
          $('#sqlConfigFields').empty()
          $('#sqlConfigWhereField').empty()

          // 移除所有关联表和条件
          $('#joinTablesContainer').find('.join-table-item:not(:first-child)').remove()
          $('#joinConditionsContainer').empty()
          $('.join-table-select').val('')

          // 取消所有字段复选框的选中状态
          $('.sql-config-field-checkbox').prop('checked', false)
        }

        // 保存SQL配置按钮点击事件
        $('#saveSqlConfigBtn').click(function () {
          saveSqlConfig()
        })

        // 加载SQL配置列表
        function loadSqlConfigs() {
          $.getJSON(`/api/datasource/${datasourceId}/sql-configs/`, function (data) {
            if (data.sql_configs && data.sql_configs.length > 0) {
              renderSqlConfigList(data.sql_configs)
            } else {
              $('#sqlConfigTableBody').html('<tr><td colspan="4" class="text-center text-muted">暂无SQL配置</td></tr>')
            }
          }).fail(function () {
            $('#sqlConfigTableBody').html('<tr><td colspan="4" class="text-center text-danger">加载SQL配置失败</td></tr>')
          })
        }

        // 渲染SQL配置列表
        function renderSqlConfigList(sqlConfigs) {
          const tbody = $('#sqlConfigTableBody')
          tbody.empty()

          sqlConfigs.forEach((config) => {
            const row = $('<tr></tr>')
            row.append(`<td>${config.name}</td>`)
            row.append(`<td>${config.description || '-'}</td>`)
            row.append(`<td>${new Date(config.created_at).toLocaleString()}</td>`)
            row.append(
              `<td>
                  <button class="btn btn-sm btn-outline-info view-sql-config" data-id="${config.id}">查看</button>
                
                  <button class="btn btn-sm btn-outline-danger delete-sql-config" data-id="${config.id}" data-name="${config.name}">删除</button>
                </td>`
            )
            tbody.append(row)
          })
        }
        // <button class="btn btn-sm btn-outline-primary edit-sql-config" data-id="${config.id}">编辑</button>
        // 使用事件委托处理动态按钮点击事件
        $(document).on('click', '.view-sql-config', function () {
          const configId = $(this).data('id')
          $.ajax({
            url: `/sql-config/${configId}/view/`,
            method: 'GET',
            success: function (data) {
              $('#viewSqlConfigName').text(data.name)
              $('#viewSqlConfigDescription').text(data.description)
              $('#viewSqlConfigSql').text(data.sql)
              $('#viewSqlConfigParams').text(data.params)
              $('#sqlConfigViewModal').modal('show')
            },
            error: function () {
              alert('加载SQL配置信息失败')
            }
          })
        })

        $(document).on('click', '.edit-sql-config', function () {
          const configId = $(this).data('id')
          editSqlConfig(configId)
        })

        $(document).on('click', '.delete-sql-config', function () {
          const configId = $(this).data('id')
          const configName = $(this).data('name')
          if (confirm('确定要删除SQL配置 "' + configName + '" 吗？')) {
            deleteSqlConfig(configId)
          }
        })

        // 加载SQL配置用的表列表（从datasourceconfig获取selected tables）
        function loadTablesForSqlConfig() {
          // 正确解析savedConfig并获取tables
          let parsedConfig
          if (typeof savedConfig === 'string') {
            try {
              parsedConfig = JSON.parse(savedConfig)
            } catch (e) {
              parsedConfig = savedConfig
            }
          } else {
            parsedConfig = savedConfig
          }

          // 从解析后的配置中获取tables
          const tables = parsedConfig.tables || []
          const selectedTables = tables.map((table) => table.table) || []

          // 为主表和关联表选择框加载表列表
          const mainTableSelect = $('.main-table-select')
          const joinTableSelects = $('.join-table-select')

          mainTableSelect.empty()
          mainTableSelect.append('<option value="">请选择主表</option>')

          joinTableSelects.empty()
          joinTableSelects.append('<option value="">请选择关联表</option>')

          if (selectedTables.length > 0) {
            selectedTables.forEach((table) => {
              mainTableSelect.append(`<option value="${table}">${table}</option>`)
              joinTableSelects.append(`<option value="${table}">${table}</option>`)
            })
          } else {
            alert('没有找到已选择的表，请先在数据暴露标签页选择表')
          }

          // 为主表选择框绑定change事件
          mainTableSelect.off('change').on('change', function () {
            const tableName = $(this).val()
            if (tableName) {
              loadFieldsForSqlConfig(tableName, 'main')
            }
          })

          // 为关联表选择框绑定change事件
          joinTableSelects.off('change').on('change', function () {
            const tableName = $(this).val()
            const joinIndex = $(this).data('join-index')
            if (tableName) {
              loadFieldsForSqlConfig(tableName, 'join', joinIndex)
            }
          })
        }

        // 加载SQL配置用的字段列表（从datasourceconfig获取selected fields）
        function loadFieldsForSqlConfig(tableName, tableType, joinIndex = 0) {
          // 正确解析savedConfig
          let parsedConfig
          if (typeof savedConfig === 'string') {
            try {
              parsedConfig = JSON.parse(savedConfig)
            } catch (e) {
              parsedConfig = savedConfig
            }
          } else {
            parsedConfig = savedConfig
          }

          // 从解析后的配置中获取指定表的字段
          const tables = parsedConfig.tables || []
          const tableConfig = tables.find((t) => t.table === tableName)
          const selectedFields = tableConfig
            ? tableConfig.fields.map((field) => {
                // 处理字段格式，去掉表名前缀
                return field.includes('.') ? field.split('.')[1] : field
              })
            : []

          if (tableType === 'main') {
            // 主表字段处理
            const fieldsContainer = $('#sqlConfigFields')
            const whereFieldSelect = $('#sqlConfigWhereField')
            fieldsContainer.empty()
            whereFieldSelect.empty()

            if (selectedFields.length > 0) {
              const fieldCheckboxes = $('<div class="form-check"></div>')

              selectedFields.forEach((field) => {
                // 添加字段复选框
                const fieldItem = $('<div class="form-check field-item"></div>')
                const fieldCheckbox = $(`
                  <input class="form-check-input sql-config-field-checkbox" type="checkbox"
                         id="sql_config_field_${tableName}_${field}"
                         data-field="${tableName}.${field}" checked>
                  <label class="form-check-label" for="sql_config_field_${tableName}_${field}">
                    ${tableName}.${field}
                  </label>
                `)
                fieldItem.append(fieldCheckbox)
                fieldCheckboxes.append(fieldItem)

                // 添加到WHERE条件字段选择
                whereFieldSelect.append(`<option value="${field}">${tableName}.${field}</option>`)
              })

              fieldsContainer.append(fieldCheckboxes)
            } else {
              fieldsContainer.html('<div class="text-muted">没有找到字段</div>')
            }
          } else if (tableType === 'join') {
            // 关联表字段处理
            const joinConditionItem = $(`#joinCondition_${joinIndex}`)
            const mainTableFieldSelect = joinConditionItem.find('.main-table-field-select')
            const joinTableFieldSelect = joinConditionItem.find('.join-table-field-select')
            const fieldsContainer = $('#sqlConfigFields')
            const whereFieldSelect = $('#sqlConfigWhereField')

            // 获取当前主表名称
            const mainTableName = $('.main-table-select').val()

            // 更新关联表字段
            joinTableFieldSelect.empty()
            if (selectedFields.length > 0) {
              selectedFields.forEach((field) => {
                joinTableFieldSelect.append(`<option value="${field}">${field}</option>`)
              })
            }

            // 更新关联表字段到fieldCheckboxes和whereFieldSelect
            if (selectedFields.length > 0) {
              // 为关联表字段创建复选框
              selectedFields.forEach((field) => {
                // 检查字段是否已存在
                if (!$(`#sql_config_field_${tableName}_${field}`).length) {
                  const fieldItem = $('<div class="form-check field-item"></div>')
                  const fieldCheckbox = $(`
                    <input class="form-check-input sql-config-field-checkbox" type="checkbox"
                           id="sql_config_field_${tableName}_${field}"
                           data-field="${tableName}.${field}" checked>
                    <label class="form-check-label" for="sql_config_field_${tableName}_${field}">
                      ${tableName}.${field}
                    </label>
                  `)
                  fieldItem.append(fieldCheckbox)
                  fieldsContainer.append(fieldItem)

                  // 添加到WHERE条件字段选择
                  whereFieldSelect.append(`<option value="${field}">${tableName}.${field}</option>`)
                }
              })
            }
          }
        }

        // 解析SQL语句获取表名、字段、关联条件和WHERE条件
        function parseSqlForConfig(sql) {
          // 简单解析，实际应用可能需要更复杂的SQL解析库
          const result = {
            mainTable: '',
            joinTables: [],
            fields: [],
            whereFields: []
          }

          // 提取SELECT后面的字段
          const selectMatch = sql.match(/SELECT\s+(.*?)\s+FROM/i)
          if (selectMatch && selectMatch[1]) {
            result.fields = selectMatch[1].split(',').map((field) => field.trim())
          }

          // 提取FROM后面的主表名
          const fromMatch = sql.match(/FROM\s+(\w+)/i)
          if (fromMatch && fromMatch[1]) {
            result.mainTable = fromMatch[1]
          }

          // 提取JOIN条件
          const joinMatches = sql.match(/LEFT\s+JOIN\s+(\w+)\s+ON\s+(\w+)\.(\w+)\s*=\s*(\w+)\.(\w+)/gi)
          if (joinMatches) {
            joinMatches.forEach((joinMatch) => {
              const details = joinMatch.match(/LEFT\s+JOIN\s+(\w+)\s+ON\s+(\w+)\.(\w+)\s*=\s*(\w+)\.(\w+)/i)
              if (details) {
                result.joinTables.push({
                  table: details[1],
                  on: {
                    mainTable: details[2],
                    mainField: details[3],
                    joinTable: details[4],
                    joinField: details[5]
                  }
                })
              }
            })
          }

          // 提取WHERE条件中的字段
          const whereMatch = sql.match(/WHERE\s+(.*)/i)
          if (whereMatch && whereMatch[1]) {
            const whereClause = whereMatch[1]
            // 简单拆分AND条件
            const conditions = whereClause.split(/AND/i)
            conditions.forEach((condition) => {
              // 提取字段名（假设格式为 field = :param 或 field = %(param)s）
              const fieldMatch = condition.match(/^(\w+\.\w+)\s*=/) || condition.match(/^(\w+\.\w+)\s+LIKE/)
              if (fieldMatch && fieldMatch[1]) {
                result.whereFields.push(fieldMatch[1])
              }
            })
          }

          return result
        }

        // 编辑SQL配置
        function editSqlConfig(configId) {
          $.getJSON(`/api/sql-config/${configId}/`, function (data) {
            $('#sqlConfigId').val(data.id)
            $('#sqlConfigName').val(data.name)
            $('#sqlConfigDescription').val(data.description || '')
            $('#sqlConfigType').val(data.config_type || 'custom')

            if (data.config_type === 'table_fields') {
              $('#customSqlSection').addClass('d-none')
              $('#customSqlParamsSection').addClass('d-none')
              $('#tableFieldsSection').removeClass('d-none')

              // 对于表字段选择类型的配置，我们需要重新生成表和字段选择界面
              loadTablesForSqlConfig()

              // 解析SQL语句以获取表名、字段和关联条件
              const sqlConfig = parseSqlForConfig(data.sql)

              // 延迟设置表名，确保表列表已加载
              setTimeout(() => {
                // 选择主表
                if (sqlConfig.mainTable) {
                  const mainTableSelect = $('.main-table-select')
                  mainTableSelect.val(sqlConfig.mainTable)
                  // 触发change事件加载字段
                  mainTableSelect.trigger('change')

                  // 添加关联表
                  if (sqlConfig.joinTables && sqlConfig.joinTables.length > 0) {
                    sqlConfig.joinTables.forEach((joinTable, index) => {
                      // 点击添加关联表按钮
                      if (index === 0) {
                        // 第一个关联表需要先清空容器
                        $('#joinTablesContainer').find('.join-table-item:not(:first-child)').remove()
                        $('#joinConditionsContainer').empty()
                      } else {
                        $('#addJoinTableBtn').trigger('click')
                      }

                      // 设置关联表名
                      setTimeout(() => {
                        const joinTableSelect = $(`.join-table-select[data-join-index="${index}"]`)
                        joinTableSelect.val(joinTable.table)
                        joinTableSelect.trigger('change')

                        // 设置关联条件
                        setTimeout(() => {
                          const joinConditionItem = $(`#joinCondition_${index}`)
                          joinConditionItem.find('.main-table-field-select').val(joinTable.on.mainField)
                          joinConditionItem.find('.join-table-field-select').val(joinTable.on.joinField)
                        }, 300)
                      }, 300)
                    })
                  }

                  // 延迟设置字段和WHERE条件，确保字段已加载
                  setTimeout(() => {
                    // 选中字段
                    sqlConfig.fields.forEach((field) => {
                      // 处理可能的表前缀
                      const fieldName = field.includes('.') ? field.split('.')[1] : field
                      const fieldId = `sql_config_field_${sqlConfig.mainTable}_${fieldName}`
                      $(`#${fieldId}`).prop('checked', true)
                    })

                    // 选中WHERE条件字段
                    if (sqlConfig.whereFields.length > 0) {
                      // 这里需要处理带表前缀的字段
                      const whereFieldSelect = $('#sqlConfigWhereField')
                      whereFieldSelect.val(sqlConfig.whereFields)
                    }
                  }, 600)
                }
              }, 300)
            } else {
              $('#customSqlSection').removeClass('d-none')
              $('#customSqlParamsSection').removeClass('d-none')
              $('#tableFieldsSection').addClass('d-none')

              $('#sqlConfigSql').val(data.sql)
              $('#sqlConfigParams').val(data.params || '')
            }

            $('#sqlConfigModalLabel').text('编辑SQL配置')
            $('#sqlConfigModal').modal('show')
          }).fail(function () {
            alert('加载SQL配置失败')
          })
        }

        // 保存SQL配置
        function saveSqlConfig() {
          const configId = $('#sqlConfigId').val()
          const name = $('#sqlConfigName').val().trim()
          const description = $('#sqlConfigDescription').val().trim()
          const configType = $('#sqlConfigType').val()

          if (!name) {
            alert('名称不能为空')
            return
          }

          let data = {
            name: name,
            description: description,
            config_type: configType,
            datasource_id: datasourceId
          }

          if (configType === 'custom') {
            const sql = $('#sqlConfigSql').val().trim()
            const params = $('#sqlConfigParams').val().trim()

            if (!sql) {
              alert('SQL语句不能为空')
              return
            }

            data.sql = sql
            data.params = params
          } else {
            const mainTableName = $('.main-table-select').val()
            const whereFields = $('#sqlConfigWhereField').val() || []
            const selectedFields = []
            const joinTables = []

            if (!mainTableName) {
              alert('请选择主表')
              return
            }

            // 收集选中的字段
            $('.sql-config-field-checkbox:checked').each(function () {
              // console.log($(this).data('field'))
              // selectedFields.push(`${mainTableName}.${$(this).data('field')}`)
              selectedFields.push(`${$(this).data('field')}`)
            })

            if (selectedFields.length === 0) {
              alert('请至少选择一个字段')
              return
            }

            // 收集关联表信息
            $('.join-table-select').each(function () {
              const joinIndex = $(this).data('join-index')
              const joinTableName = $(this).val()
              if (joinTableName && joinTableName !== mainTableName) {
                const joinConditionItem = $(`#joinCondition_${joinIndex}`)
                const mainTableField = joinConditionItem.find('.main-table-field-select').val()
                const joinTableField = joinConditionItem.find('.join-table-field-select').val()

                if (mainTableField && joinTableField) {
                  joinTables.push({
                    table: joinTableName,
                    on: {
                      mainTable: mainTableName,
                      mainField: mainTableField,
                      joinTable: joinTableName,
                      joinField: joinTableField
                    }
                  })
                }
              }
            })

            // 生成SQL语句
            const fieldsStr = selectedFields.join(', ')
            console.log('111', fieldsStr)
            let sql = `SELECT ${fieldsStr} FROM ${mainTableName}`

            // 添加JOIN语句
            joinTables.forEach((joinTable) => {
              sql += ` LEFT JOIN ${joinTable.table} ON ${joinTable.on.mainTable}.${joinTable.on.mainField} = ${joinTable.on.joinTable}.${joinTable.on.joinField}`
            })

            // 添加WHERE条件
            const params = []
            if (whereFields && whereFields.length > 0) {
              const whereConditions = []
              whereFields.forEach((field, index) => {
                // 处理带表前缀的字段
                const fieldName = field.includes('.') ? field : `${mainTableName}.${field}`
                const paramName = field.replace('.', '_')
                whereConditions.push(`${fieldName} = %(${paramName})s`)
                params.push(paramName)
              })
              sql += ` WHERE ${whereConditions.join(' AND ')}`
            }

            data.sql = sql
            data.params = params.join(';')
          }

          let url = '/api/sql-config/create/'
          let method = 'POST'

          if (configId) {
            url = `/api/sql-config/${configId}/update/`
            method = 'PUT'
          }

          console.log(url, method, data)

          $.ajax({
            url: url,
            type: method,
            data: JSON.stringify(data),
            contentType: 'application/json',
            headers: {
              'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').val()
            },
            success: function () {
              $('#sqlConfigModal').modal('hide')
              loadSqlConfigs()
              alert('SQL配置保存成功')
            },
            error: function () {
              alert('SQL配置保存失败')
            }
          })
        }

        // 删除SQL配置
        function deleteSqlConfig(configId) {
          $.ajax({
            url: `/api/sql-config/${configId}/delete/`,
            type: 'DELETE',
            headers: {
              'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').val()
            },
            success: function () {
              loadSqlConfigs()
              alert('SQL配置删除成功')
            },
            error: function () {
              alert('SQL配置删除失败')
            }
          })
        }

        // 加载表和字段信息
        $.getJSON(`/api/datasource/${datasourceId}/tables/`, function (data) {
          if (data.tables && data.tables.length > 0) {
            renderTableSelection(data.tables)
            this.table_count = data.tables.length
            console.log(this.table_count)
            console.log(data.tables)

            // 应用已保存的配置
            applySavedConfig(savedConfig)
          } else {
            $('#tableSelectionSection').html('<div class="alert alert-warning">未发现任何数据表</div>')
          }
        }).fail(function () {
          $('#tableSelectionSection').html('<div class="alert alert-danger">加载表信息失败，请刷新页面重试</div>')
        })

        // 渲染表和字段选择UI
        function renderTableSelection(tables) {
          const container = $('#tableSelectionSection')
          container.empty()
          table_count = tables.length
          tables.forEach((table) => {
            // 创建表容器
            const tableItem = $('<div class="table-item"></div>')

            // 表标题和复选框
            const tableHeader = $('<div class="table-header d-flex align-items-center"></div>')
            const tableCheckbox = $(`
                      <div class="form-check form-switch me-2">
                          <input class="form-check-input table-checkbox" type="checkbox" id="table_${table.name}" data-table="${table.name}">
                          <label class="form-check-label" for="table_${table.name}">${table.name}</label>
                      </div>
                  `)
            const tableBadge = $(`<span class="badge bg-secondary">${table.field_count}个字段</span>`)

            tableHeader.append(tableCheckbox)
            tableHeader.append(tableBadge)
            tableItem.append(tableHeader)

            // 字段容器
            const fieldsContainer = $(`<div class="table-fields d-none" id="fields_${table.name}"></div>`)

            // 添加字段复选框
            table.fields.forEach((field) => {
              const fieldItem = $('<div class="form-check field-item"></div>')
              const fieldCheckbox = $(`
                          <input class="form-check-input field-checkbox" type="checkbox" name="fields"
                               value="${table.name}.${field.name}" id="field_${table.name}_${field.name}" data-table="${table.name}">
                          <label class="form-check-label d-flex flex-wrap align-items-center gap-2" for="field_${table.name}_${field.name}">
                              <span class="font-medium">${field.name}</span>
                              <span class="field-type text-sm">${field.type}</span>
                              ${field.description ? `<span class="field-description text-sm">${field.description}</span>` : ''}
                              ${field.nullable ? '<span class="badge nullable-badge text-xs">可为空</span>' : '<span class="badge not-nullable-badge text-xs">必填</span>'}
                          </label>
                      `)
              fieldItem.append(fieldCheckbox)
              fieldsContainer.append(fieldItem)
            })

            tableItem.append(fieldsContainer)
            container.append(tableItem)

            // 表复选框事件处理
            tableCheckbox.find('input').change(function () {
              const isChecked = $(this).prop('checked')
              const fieldsContainer = $(`#fields_${table.name}`)
              const fieldCheckboxes = fieldsContainer.find('.field-checkbox')

              // 显示/隐藏字段
              fieldsContainer.toggleClass('d-none', !isChecked)

              // 全选/取消全选字段
              fieldCheckboxes.prop('checked', isChecked)
            })
          })
        }

        // 全选按钮事件
        $('#selectAllBtn').click(function () {
          $('.table-checkbox').prop('checked', true).trigger('change')
        })

        // 取消全选按钮事件
        $('#deselectAllBtn').click(function () {
          $('.table-checkbox').prop('checked', false).trigger('change')
        })

        // 应用已保存的配置
        function applySavedConfig(config) {
          // 解析保存的配置
          let parsedConfig
          if (typeof config === 'string') {
            try {
              parsedConfig = JSON.parse(config)
            } catch (e) {
              parsedConfig = config
            }
          } else {
            parsedConfig = config
          }

          console.log('Applying saved config:', parsedConfig.tables)
          if (!parsedConfig || !parsedConfig.tables) {
            return
          }
          // 遍历已保存的表配置
          parsedConfig.tables.forEach(function (savedTable) {
            const tableCheckbox = $(`#table_${savedTable.table}`)
            const fieldsContainer = $(`#fields_${savedTable.table}`)

            // 选中表复选框
            tableCheckbox.prop('checked', true)

            // 显示字段容器
            fieldsContainer.removeClass('d-none')

            // 选中对应的字段
            savedTable.fields.forEach(function (savedField) {
              // 处理字段名格式，支持 "table.field" 或直接 "field"
              const fieldName = savedField.includes('.') ? savedField.split('.')[1] : savedField
              const fieldId = `field_${savedTable.table}_${fieldName}`
              $(`#${fieldId}`).prop('checked', true)
            })
          })
        }

        // 保存配置到数据库按钮事件
        $('#saveToDbBtn').click(function () {
          const selectedTables = []

          // 收集选择的表和字段
          $('.table-checkbox:checked').each(function () {
            const tableName = $(this).data('table')
            const selectedFields = []

            $(`#fields_${tableName} .field-checkbox:checked`).each(function () {
              selectedFields.push($(this).val())
            })

            if (selectedFields.length > 0) {
              selectedTables.push({
                table: tableName,
                fields: selectedFields
              })
            }
          })

          if (selectedTables.length === 0) {
            alert('请至少选择一个表和字段')
            return
          }

          // 发送到服务器保存
          $.ajax({
            url: `/${datasourceId}/config/`,
            type: 'POST',
            data: JSON.stringify({
              selected_tables: selectedTables
            }),
            contentType: 'application/json',
            headers: {
              'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').val()
            },
            success: function (response) {
              if (response.status === 'success') {
                alert('配置保存成功！')

                // 更新savedConfig变量，以便SQL配置能获取到最新的表列表
                const newConfig = {
                  tables: selectedTables
                }
                // 更新全局savedConfig变量
                savedConfig = JSON.stringify(newConfig)

                // 如果当前在SQL配置标签页，则立即更新表列表
                if ($('#sql-config-tab').hasClass('active')) {
                  updateSqlConfigTables()
                }
              } else {
                alert('保存失败：' + response.message)
              }
            },
            error: function () {
              alert('保存失败，请检查网络连接')
            }
          })
        })

        // 更新SQL配置的表列表
        function updateSqlConfigTables() {
          // 重新加载SQL配置的表列表
          loadTablesForSqlConfig()
        }

        // 保存配置到JSON按钮事件
        $('#saveConfigBtn').click(function () {
          const selectedTables = []

          // 收集选择的表和字段
          $('.table-checkbox:checked').each(function () {
            const tableName = $(this).data('table')
            const selectedFields = []

            $(`#fields_${tableName} .field-checkbox:checked`).each(function () {
              selectedFields.push($(this).val())
            })

            if (selectedFields.length > 0) {
              selectedTables.push({
                table: tableName,
                fields: selectedFields
              })
            }
          })

          if (selectedTables.length === 0) {
            alert('请至少选择一个表和字段')
            return
          }

          // 生成配置JSON
          const config = {
            datasource: {
              id: datasourceId,
              name: '{{ datasource.name }}',
              engine: '{{ datasource.engine }}',
              host: '{{ datasource.host }}',
              port: '{{ datasource.port }}',
              database: '{{ datasource.database }}',
              username: '{{ datasource.username }}'
            },
            tables: selectedTables,
            created_at: new Date().toISOString()
          }

          // 创建并下载JSON文件
          const jsonStr = JSON.stringify(config, null, 2)
          const blob = new Blob([jsonStr], { type: 'application/json' })
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = `{{ datasource.name }}_config.json`
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          URL.revokeObjectURL(url)
        })
      })
    </script>
  </body>
</html>
